window.GlobalMsg = {
    //自增ID
    msgID: 0,
    //事件列表
    msgMap: new Map(),
    //监听者列表
    listenerMap: new Map(),
    //
    interval: null,

    //启动
    Start:function() {
        let self = this;
        this.interval = setInterval(function() {
            self.Update(100);
        }, 100);
    },
    //停止
    Stop:function() {
        if (this.interval) {
            clearInterval(this.interval);
        }
    },
    //增加消息监听
    AddListener:function(msgType, callback, object){//参数：消息名，回调函数，回调对象
        //回调对象
        let msgListener = {
            callback: callback,
            target: object,
        };

        let listener = this.listenerMap.get(msgType);
        if (listener!=null) {
            listener.push(msgListener);
        }
        else{
            let arr = new Array(msgListener);
            this.listenerMap.set(msgType, arr);
        }
    },
    //发消息
    PostMsg:function(msgType, millisecon, msgData=null){//参数：消息名，延时豪秒，消息数据
        this.msgID++;
        if (this.msgID > 200000000) {
            this.msgID = 1;
        }
        //事件对象
        let msgEvent = {
            msgType: msgType,
            data: msgData,
            time: millisecon,
        };
        this.msgMap.set(this.msgID, msgEvent);
        return this.msgID;
    },
    //更新队列
    Update:function(millisecon){
        let self = this;
        let del = [];
        this.msgMap.forEach(function(v,k) {
            v.time -= millisecon;
            if (v.time < 0) {
                let listener = self.listenerMap.get(v.msgType);
                if (listener) {
                    for (let j = 0; j < listener.length; j++) {
                        listener[j].callback.call(listener[j].target, v.data);
                    }
                }
                del.push(k);
            }
        });
        for (let i = 0; i < del.length; i++) {
            this.msgMap.delete(del[i]);
        }
    },
    //删除一条消息
    DeleteMsg:function(msgID){
        if (this.msgMap.has(msgID)) {
            this.msgMap.delete(msgID);
        }
    },
    //删除回调,删除该消息类型的所有回调
    DeleteListenerByType:function(msgType){
        if (this.listenerMap.has(msgType)) {
            this.listenerMap.delete(msgType);
        }
    },
    //删除回调,删除该消息类型的一个回调
    DeleteListenerByTarget:function(msgType, target){
        let listener = this.listenerMap.get(msgType);
        if (listener!=null) {
            for (let i = 0; i < listener.length; i++) {
                if (listener[i].target===target) {
                    listener.splice(i,1);
                    break;
                }
            }
        }
    }
};
